package test0319;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/3/19 22:12
 * 有三个线程，分别只能打印A，B和C
 * 要求按顺序打印ABC，打印10次
 * 输出示例：
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 */
public class Main01 {

    static Object loopA = new Object();
    static Object loopB = new Object();
    static Object loopC = new Object();

    public static void main(String[] args) throws InterruptedException {
        // t1 线程负责打印 A
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    synchronized (loopA) {
                        loopA.wait();
                    }
                    System.out.print("A");
                    synchronized (loopB) {
                        loopB.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        // t2 线程负责打印 B
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    synchronized (loopB) {
                        loopB.wait();
                    }
                    System.out.print("B");
                    synchronized (loopC) {
                        loopC.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t3 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    synchronized (loopC) {
                        loopC.wait();
                    }
                    System.out.println("C");
                    synchronized (loopA) {
                        loopA.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();

        Thread.sleep(1000);

        // 从 t1 线程开始
        synchronized (loopA) {
            loopA.notify();
        }

    }
}
